package com.maomao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.maomao.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@RestController
public class MovieController {
	
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@HystrixCommand(fallbackMethod = "findByIdFallback" , commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000"),
			@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000")
	},threadPoolProperties = {
			@HystrixProperty(name = "coreSize",value = "1"),
			@HystrixProperty(name = "maxQueueSize",value = "10")
	})
	@GetMapping("/movie/{id}")
	public User findById(@PathVariable Integer id){
		return this.restTemplate.getForObject("http://provider-user/user/"+id, User.class);
	}
	
	@GetMapping("/test")
	public String test(){
		ServiceInstance  serviceInstance = this.loadBalancerClient.choose("provider-user");
		System.out.println(serviceInstance.getPort()+":"+serviceInstance.getServiceId());
		return "ok";
	}

	
	public User findByIdFallback(Integer id){
		User user = new User();
		user.setId(-1);
		user.setUserName("默认用户");
		return user;
	}
}
